<?php

namespace Beerus\Modules\Wiki\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\wiki\ObjRelateWiki as mObjRelateWiki;
use Biz\module\Classes\wiki\RelateWiki as clsRelateWiki;
use Biz\service\search\Goods as sGoods;
use Biz\service\wiki\AdmWiki as sWiki;
use Biz\service\wiki\ObjRelateWiki as sObjRelateWiki;
use Doraemon\model\Member as mMember;
use Doraemon\model\Photos as mPhotos;
use Doraemon\model\PicStickers as mPicStickers;
use Doraemon\service\Photos as sPhotos;
use Doraemon\tools\IdParse;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class ObjRelateWikiController extends Controller
{

    const PAGE_SIZE = 50;
    const AUTH_USER_NORMAL = mMember::USER_COMMON; //普通用户
    const AUTH_USER_BRAND = mMember::AUTH_USER_BRAND;  //品牌用户
    const AUTH_USER_DESIGNER = mMember::AUTH_USER_DESIGNER;  //设计师用户
    const AUTH_USER_MEDIA = mMember::AUTH_USER_V;  //媒体用户
    const AUTH_USER_EXAMPLE = mMember::AUTH_USER_EXAMPLE;  //居住榜样用户
    const AUTH_USER_MAP = [
        self::AUTH_USER_NORMAL => '普通用户',
        self::AUTH_USER_BRAND => '品牌用户',
        self::AUTH_USER_DESIGNER => '设计师用户',
        self::AUTH_USER_MEDIA => '媒体用户',
        self::AUTH_USER_EXAMPLE => '居住榜样用户',
    ];

    public function __construct()
    {
        parent::__construct();

        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function delRelate(Request $request, $note_id)
    {
        $code = 200;
        $message = '删除关联成功';
        try {
            $objId = $request->post('goodsId', 0);//删除的wiki_id
            $isWiki = $request->post('isWiki', 0);//删除的商品类型
            $wikiId = $isWiki > 0 ? $objId : 0;
            $goodsId = $isWiki > 0 ? 0 : $objId;
            $type = $request->post('type', 0);//类型
            if ($type != mObjRelateWiki::TYPE_ARTIFICIAL) {
                throw new \Exception('运营只允许解除运营自己挂的wiki');
            }
            $rs = sObjRelateWiki::admNoteRemoveRelate($note_id, Admin::user()->id, $goodsId, $wikiId, $type = mObjRelateWiki::TYPE_ARTIFICIAL);
            if (!$rs) {
                throw new \Exception('更新不成功');
            }
            if ($wikiId > 0) {
                $uid = IdParse::getUid($note_id);

                clsRelateWiki::afterRelateWiki($uid, [$wikiId], $note_id, mObjRelateWiki::OBJ_TYPE_NOTE);

                //更新缓存
                sObjRelateWiki::admAfterSaveDelCache($note_id);
            }
        } catch (\Exception $e) {
            $code = 0;
            $message = $e->getMessage();
        }
        return response()->json(compact('code', 'message'));
    }

    public function saveRelate(Request $request, $note_id)
    {
        try {
            $wikiIds = $request->post('wikiIds', []);//添加的wiki_id
            $goodsIds = $request->post('goodsIds', []);//添加的商品id
            $picId = $request->post('picId', '');//关联的图片

            if (!$note_id) {
                throw new \Exception('没有关联的note');
            }

            if (empty($wikiIds)) {
                throw new \Exception('没有关联的wiki');
            }

            //入库关联
            if (!empty($wikiIds)) {

                //图片关联wiki
                foreach ($wikiIds as $wiki) {
                    try {
                        sObjRelateWiki::admNoteRelate($note_id, $picId, Admin::user()->id, $wiki);
                    } catch (\Exception $e) {
                        continue;
                    }
                }
                $uid = IdParse::getUid($note_id);

                clsRelateWiki::afterRelateWiki($uid, [$wiki], $note_id, mObjRelateWiki::OBJ_TYPE_NOTE);

                //更新缓存
                sObjRelateWiki::admAfterSaveDelCache($note_id);
            }
            $success = new MessageBag([
                'title' => '关联成功'
            ]);
            return redirect('/admin/wiki/relateWiki/' . $note_id)->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '关联失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function wikiSearch(Request $request)
    {
        $keyword = $request->post('keyword', '');
        $page = $request->post('offset', 1);
        $wiki = $request->get('wiki', 0);
        $pageSize = 40;
        $page = ($page <= 0) ? 1 : $page;
        $defaultResponse = ['list' => [], 'is_over' => 1, 'count' => 0];
        switch ($wiki) {
            case 0:
                $productInfo = strlen($keyword) ? sGoods::searchGoodsOnPubPhoto($keyword, $page, $pageSize) : $defaultResponse;
                break;
            case 1:
                $productInfo = strlen($keyword) ? sObjRelateWiki::admListWikiByKeyword($keyword, $page, $pageSize) : $defaultResponse;
                break;
            case 2:
                $ids = str_replace("，", ',', trim($keyword));
                $ids = strlen($ids) ? explode(",", $ids) : [];
                $productInfo = strlen($keyword) ? sObjRelateWiki::admListWikiByIds($ids, $page, $pageSize) : $defaultResponse;
                break;
        }

        $productInfo['page'] = $page;
        $productInfo['wiki'] = $wiki;
        echo json_encode($productInfo, JSON_UNESCAPED_UNICODE);
    }

    private function wikiScript()
    {
        return <<<SCRIPT
    //加载搜索数据
    function loadMulti(e) {
        let obj = $(e).parents('.img_item').find(".storePool")
        $.post(searchUrl, {
            'keyword': keyWord,
            'offset': page
        }, function (data) {
            let html = '';
            let dataList = data.list;
            let requestPage = parseInt(data.page);
            let requestWiki = parseInt(data.wiki);
            let responseCount = data.count == undefined ? 0 : parseInt(data.count);
            let is_over = data.is_over;
            for (let i  in dataList) {
                html += ' <div class="storeinfo" >' +
                    ' <img wiki-id="' + requestWiki + '" store-id="' + dataList[i]['id'] + '" src="' + dataList[i]['cover_img'] + '"/> <br> ' +
                    '<small> ' + dataList[i]['title'] + ' </small> ' +
                    '<small> ' + dataList[i]['shop_info']['name']  + '(' + dataList[i]['shop_info']['uid'] + ') </small> ' +
                    ' </div> ';
            }


            if (requestPage <= 1) {
                obj.show();
                $(".panel-bottom").show();
                obj.find('div.panel-heading > span#title').html("检索出" + responseCount + "件商品");
                obj.find('.panel-body').html(html);
            } else  {
                obj.find('.panel-body').append(html);
            }

            if (is_over > 0) {
                $(".panel-bottom").hide();
            }
        }, 'json');
        page++;
    }

    let page = 1;//搜索页码
    let keyWord = '';//搜索关键字
    let searchUrl = '';//搜索控制器
    
    //提交表单前校验
    $('.form1').submit(function(){
        let spuCheck = $(this).find("input[name='goodsIds[]']").val() > 0
        let wikiCheck = $(this).find("input[name='wikiIds[]']").val() > 0
        if (!spuCheck && !wikiCheck) {
            layer.msg("未添加关联");
            return false;
        }
    });
    //加载更多
    $('.storePool').delegate('.panel-bottom','click', function(){
        loadMulti(this);
    });
    //选择商品
    $('.storePool').delegate('.storeinfo','click', function(){
        let storeid = $(this).find('img').attr('store-id');
        let storesrc = $(this).find('img').attr('src');
        let storewiki = $(this).find('img').attr('wiki-id') > 0 ? 'wiki' : 'spu';
        let storename = $(this).find('small').text();

        let temp = '<div style="border-bottom:1px solid black" store-id="' + storewiki + storeid + '"> ' +
            '<img src="' + storesrc + '" height="50px" width="50px"/> ' +
            '<span> [ '+ storewiki + ':' + storeid + ' ] ' + storename +' | </span>' +
            (storewiki == 'spu' ? '<input type="hidden" name="goodsIds[]" value=' + storeid + '>' : '<input type="hidden" name="wikiIds[]" value=' + storeid + '>') +
            '<a class="del" >取消关联</a> <br> </div>';
        $(this).parents('.img_item').find('div.goods-group').append(temp);
        $(this).parents('.img_item').find(".storePool").hide();
    });
    //取消关联
    $(".goods-group").delegate('.del', 'click', function(){
        $(this).parent('div[store-id]').remove();
    })
    //复制链接
    $.getScript('/vendor/js/clipboard/dist/clipboard.min.js', function(){
    //避免pjax重复加载js导致事件重复绑定
        if (typeof (pjax_isLoad) != "undefined") {
            return;
        } 
        pjax_isLoad = true;
        let copyBtn = new ClipboardJS(".copyLink", {
        text: function(e) {
              return $(e).find(':input').val();
            }
    });
        copyBtn.on("success",function(e){
            // 复制成功
             if (e.text.length > 0) {
                toastr.success('复制成功');
             }
             e.clearSelection();
        });
        copyBtn.on("error",function(e){
            //复制失败
            console.log( e.action )
        });
});

    //删除关联
    $(".deleteRel").click(function(){
            let noteId = $(this).parent().attr('photo-id');
            let delData = {
                photoId : $(this).parent().attr('photo-id'),
                goodsId : $(this).parent().attr('goods-id'),
                isWiki : $(this).parent().attr('wiki-id'),
                type : $(this).parent().attr('type-id')
            };
            let uid = $(this).attr('data-uid');
        swal({
        title: "确认删除吗？",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        showLoaderOnConfirm: true,
        cancelButtonText: "取消",
        preConfirm: function() {
            $.ajax({
                type: "POST",
                url: '/admin/wiki/relateWiki/' + noteId + '/delRelate',
                dataType: 'json',
                data: delData,
                success: function (data) {
                    if (data.code === 200) {
                        $('#divgood_'+ uid).remove();
                        layer.msg(data.message);
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        }
        });
    });
    //关闭搜索框
    $(".close").click(function(){
        $(this).parents('.img_item').find(".storePool").hide();
    })
    //选择图片
    $("img.pics").click(function () {
        var picid = $(this).attr('data-id');
        let hasClass = $(this).hasClass('active');
        $(".pics").removeClass('active');
        if (hasClass) {
            $("input[name=picId]").val("");
        } else {
            $(this).addClass('active')
            $("input[name=picId]").val(picid);
        }
    });
    //搜索输入事件
    $('.keywordSearch').keyup(function () {
        keyWord = $(this).val().trim();
        if (keyWord.length > 0) {
            searchUrl = '/admin/wiki/relateWiki/search'
            page = 1;
            loadMulti($(this).parents('.img_item').find(".panel-bottom"));
        } else {
            $(this).parents('.img_item').find(".storePool").hide()
        }
    });
    //搜索输入事件wiki
    $('.keywordSearchWiki').keyup(function () {
        keyWord = $(this).val().trim();
        if (keyWord.length > 0) {
            searchUrl = '/admin/wiki/relateWiki/search?wiki=1'
            page = 1;
            loadMulti($(this).parents('.img_item').find(".panel-bottom"));
        } else {
            $(this).parents('.img_item').find(".storePool").hide()
        }
    });
    //搜索输入事件wiki
    $('.keywordSearchWikiId').keyup(function () {
        keyWord = $(this).val().trim();
        if (keyWord.length > 0) {
            searchUrl = '/admin/wiki/relateWiki/search?wiki=2'
            page = 1;
            loadMulti($(this).parents('.img_item').find(".panel-bottom"));
        } else {
            $(this).parents('.img_item').find(".storePool").hide()
        }
    });
SCRIPT;

    }

    public function wiki(Request $request, Content $content, $pic_id)
    {
        try {
            $photoInfo = mPhotos::getPhoto($pic_id);
            if ($photoInfo) {
                //格式化点图标签
                $stickers = mPicStickers::getStickersByNoteId($pic_id);
                $stickersMap = empty($stickers) ? [] : array_column($stickers, 'img_tags', 'pic_id');
                $imgTag = array_map(function ($v) {
                    return sObjRelateWiki::admFormatImgTags($v);
                }, $stickersMap);

                $picList = sPhotos::getImageList($photoInfo['pic_list']);

                //图片关联商品
                $relateInfo = sObjRelateWiki::admNoteRelateList($pic_id);

                //组装数据
                $picList = array_map(function ($v) use ($relateInfo, $imgTag) {
                    $v['relateList'] = isset($relateInfo[$v['pic_id']]) ? $relateInfo[$v['pic_id']]['list'] : [];
                    $v['imgTag'] = isset($imgTag[$v['pic_id']]) ? $imgTag[$v['pic_id']] : "";
                    return $v;
                }, $picList);
            } else {
                throw new \Exception('图片不存在! 请检查图片状态');
            }
            Admin::script($this->wikiScript());
            return $content
                ->header('编辑note关联wiki')
                ->description(' ')
                ->breadcrumb(
                    ['text' => 'note关联wiki列表', 'url' => '/wiki/relateWiki'],
                    ['text' => '编辑note关联wiki']
                )
                ->row(view('wiki::relate.relateWiki', compact('picList', 'pic_id')));
        } catch (\Exception $e) {
            echo '错误提示:', $e->getFile(), $e->getLine(), $e->getMessage();
        }
    }

    public function index(Request $request, Content $content)
    {
        $scoreMap = [
            0 => '未打分',
            1 => '1-10分',
            2 => '11-59分',
            3 => '60-79分',
            4 => '80-100分',
        ];

        $requestParams = $request->all();
        $condition = $this->_index_condition($requestParams);
        $category_id = isset($requestParams['category_id']) ? $requestParams['category_id'] : 0;

        $pageSize = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];

        $photoList = sWiki::admSearchPhotoList($condition);
        $gridModel = new pGridDataModel($photoList['list'], $photoList['total'], [
            'perPage' => $pageSize
        ]);

        return $content
            ->header('note关联wiki列表')
            ->description(' ')
            ->row(
                Admin::grid($gridModel,
                    function (Grid $grid) use ($gridModel, $category_id, $scoreMap, $condition) {
                        $grid->paginate($gridModel->getPerPage());
                        $grid->filter(function ($filter) use ($category_id, $scoreMap, $condition) {

                            // 去掉默认的id过滤器
                            $filter->disableIdFilter();

                            // 在这里添加字段过滤器
                            $filter->column(1 / 2, function ($filter) use ($scoreMap) {
                                $filter->equal('user_type', '用户身份')->checkbox(self::AUTH_USER_MAP);
                                $filter->equal('score', '分数')->checkbox($scoreMap);
                                $filter->equal('has_goods', '已关联商品')->select([1 => '是', 2 => '否']);

                                $filter->equal('tag', '标签')->placeholder('请输入标签');
                                $filter->equal('pic_id', '图片id')->placeholder('请输入图片id');
                                $filter->equal('uid', '用户uid')->placeholder('请输入用户uid');
                            });

                            $filter->column(1 / 2, function ($filter) use ($condition) {
                                //时间筛选
                                $filter->between('date_time', '发图时间')->datetime()->condition(['date_time' => [
                                    'start' => $condition['add_start'],
                                    'end' => $condition['add_end'],
                                ]]);

                                $filter->dropDown('ideaBook', [
//                                    'idea_book_name'    => '灵感集名称',
                                    'idea_book_id' => '灵感集ID',
                                ]);
                                $filter->dropDown('topic', [
                                    'topic_id' => '话题ID',
                                    'topic_name' => '话题名称',
                                ]);
                                $filter->dropDown('article', [
                                    'article_id' => '整屋ID',
                                    'article_name' => '整屋名称',
                                ]);

                                $filter->equal('sort', '排序')->radio([0 => '默认', 1 => '热度']);
                            });

                            $filter->expand();//默认展开
                        });
                        $grid->disableExport();
                        $grid->disableCreateButton();
                        $grid->disableRowSelector();

                        $grid->column('pic_id', '图片id');
                        $grid->column('nick', '用户昵称');
                        $grid->column('cover_img_url', '首图')->display(function () {
                            $imgPath = $this->cover_img_url;
                            $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='max-height:100px' class='img img-thumbnail' />" : "";
                            return $image;
                        });
                        $grid->column('addtime', '发布时间');
                        $grid->column('remark', '发布内容')->display(function () {
                            return '<div ><textarea>' . $this->remark . '</textarea></div>';
                        });

                        $grid->actions(function (Grid\Displayers\Actions $actions) {
                            $actions->disableDelete();
                            $actions->disableEdit();
                            $actions->prepend('<a class="fa fa-chain" target ="_blank" href="' . 'relateWiki/' . $actions->row->pic_id . '">关联商品</a>');
                        });
                    }
                )
            );
    }

    public function _index_condition($request)
    {
        $response = [];

        //用户身份
        if (isset($request['user_type']) && !empty($request['user_type'])) {
            $response['user_type'] = implode(',', $request['user_type']);
        }

        //分数
        if (isset($request['score']) && !empty($request['score'])) {
            if (in_array(0, $request['score'])) {
                $response['min_score'] = 0;
                $response['max_score'] = 0;
            }
            if (in_array(1, $request['score'])) {
                $response['min_score'] = isset($response['min_score']) ? $response['min_score'] : 1;
                $response['max_score'] = 10;
            }
            if (in_array(2, $request['score'])) {
                $response['min_score'] = isset($response['min_score']) ? $response['min_score'] : 11;
                $response['max_score'] = 59;
            }
            if (in_array(3, $request['score'])) {
                $response['min_score'] = isset($response['min_score']) ? $response['min_score'] : 60;
                $response['max_score'] = 79;
            }
            if (in_array(4, $request['score'])) {
                $response['min_score'] = isset($response['min_score']) ? $response['min_score'] : 80;
                $response['max_score'] = 100;
            }
        }

        //是否关联商品   1为取包含商品的，2为取不包含商品的
        if (isset($request['has_goods']) && ($request['has_goods'] > 0)) {
            $response['has_goods'] = intval($request['has_goods']);
        }

        //创建时间条件
        $earliestDate = '2015-11-01 00:00:00';
        $defaultStartDate = date("Y-m-d 00:00:00");
        $defaultEndDate = date("Y-m-d 23:59:59");
        $startDateCheck = isset($request['date_time']['start']) && strlen($request['date_time']['start']);
        $endDateCheck = isset($request['date_time']['end']) && strlen($request['date_time']['end']);

        if (!$startDateCheck && !$endDateCheck) {
            $response['add_start'] = $defaultStartDate;
            $response['add_end'] = $defaultEndDate;
        }
        if ($startDateCheck && !$endDateCheck) {
            $response['add_start'] = $request['date_time']['start'];
            $response['add_end'] = $defaultEndDate;
        }
        if (!$startDateCheck && $endDateCheck) {
            $response['add_start'] = $earliestDate;
            $response['add_end'] = $request['date_time']['end'];
        }
        if ($startDateCheck && $endDateCheck) {
            $response['add_start'] = $request['date_time']['start'];
            $response['add_end'] = $request['date_time']['end'];
        }


        //标签
        if (isset($request['tag']) && strlen(trim($request['tag']))) {
            $response['keyword'] = trim($request['tag']);
        }

        //图片id
        if (isset($request['pic_id']) && strlen(trim($request['pic_id']))) {
            $response['id'] = trim($request['pic_id']);
        }

        //用户uid
        if (isset($request['uid']) && ($request['uid'] > 0)) {
            $response['uid'] = intval($request['uid']);
        }

        //灵感集
        $nullPicId = ' ';
        if (isset($request['idea_book_id']) || isset($request['idea_book_name'])) {
            $pic_id = $nullPicId;
            if (!empty($request['idea_book_id'])) {
                $pic_id = sWiki::admGetPicByIdeaBook(intval($request['idea_book_id']));
            }
            if (!empty($request['idea_book_name'])) {
                $idea_book_name = $request['idea_book_name'];
                $pic_id = sWiki::admGetPicByIdeaBookName($idea_book_name);
            }
            if (!empty($request['idea_book_id']) || !empty($request['idea_book_name'])) {
                if (isset($response['id'])) {
                    $pic_id = in_array($response['id'], $pic_id) ? $response['id'] : $nullPicId;
                } else {
                    $pic_id = empty($pic_id) ? $nullPicId : $pic_id;
                }
                if (is_array($pic_id)) {
                    $response['ids'] = implode(',', $pic_id);
                } else {
                    $response['id'] = $pic_id;
                }
            }
        }

        //话题
        if (isset($request['topic_name']) && strlen(trim($request['topic_name']))) {
            $topicIds = sWiki::admGetTopicIdByName($request['topic_name']);
            $response['topic_activity_ids'] = empty($topicIds) ? $nullPicId : implode(',', $topicIds);
        }

        if (isset($request['topic_id']) && ($request['topic_id'] > 0)) {
            $response['topic_activity_id'] = $request['topic_id'];
        }

        //整屋
        $articleIds = [];
        if (isset($request['article_name']) && strlen(trim($request['article_name']))) {
            //查询articleIds
            $articleIds = sWiki::admGetArticleIdByName($request['article_name']);
            $response['article_ids'] = $articleIds;
        }
        if (isset($request['article_id']) && (strlen(trim($request['article_id'])) > 0)) {
            $articleIds[] = $request['article_id'];
        }
        $response['article_ids'] = empty($articleIds) ? '' : implode(',', $articleIds);

        //排序
        if (isset($request['sort']) && ($request['sort'] > 0)) {
            $response['sort'] = 'hotrank';
        }


        return $response;
    }

    private function imgSubmitScript()
    {
        $uploadUrl = url('admin/extend/img/uploadtossoori');
        return <<<EOD
        let inputs = $('input[file-upload]');
        inputs.each(function () {
            let imgList = $(this).attr('file-upload') + '-list';
            let src = $(this).attr('data-files');
            let source_src = $(this).attr('source-files');
            let src_str = '';
            let srcLen = src.length;
            let srcArr = srcLen > 0 ? src.split(',') : [];
            srcLen = srcArr.length;
            let tempLen = 0;
            let tempArr = [];
            let ext = '';
            let initConfig = [];
            for (let i=0; i < srcLen; i++) {
                src_str = srcArr[i];
                tempArr = src_str.split('.');
                tempLen = tempArr.length;
                ext = tempArr[tempLen - 1];
                switch (ext) {
                    case 'PDF':
                        ext = 'pdf';break;
                    default:
                        ext = 'image' ;break;
                }
                initConfig.push({type: ext, key : i});
            }
            console.log(srcArr);
            console.log(initConfig);

            let imgs = source_src.length > 0 ? source_src.split(',') : [];
            let source_images = imgs;
            let load_images = [];
            $(this).fileinput({
                validateInitialCount : true,
                initialPreview: srcArr,
                initialPreviewConfig: initConfig,
                deleteUrl: '/admin/extend/img/imgdelete',
                //uploadUrl: '$uploadUrl',
                language: "zh",
                maxFileSize : 10000,
                maxFileCount : 10,
                showRemove: false,
                showUpload: false,
                showCaption: false,
                showCancel: false,
                overwriteInitial: false,
                initialPreviewAsData: true,
                fileActionSettings: {showDrag: true, showUpload: false},
                allowedFileExtensions: ["pdf", "jpg", "png"],
                previewSettings: {
                    image: {width: "180px"},
                    type:"pdf",
                },
                showBrowse: false,
                browseLabel: '选择文件',
                msgFilesTooMany: "禁止上传文件.",
                msgSizeTooLarge: "文件 {name} (<b>{size} KB</b>) 超过了允许大小 <b>{maxSize} KB</b>.",
                layoutTemplates: {progress: ''}
            }).on('filebatchselected', function () {
                //选择文件
                $(this).fileinput('upload');
            }).on('fileuploaded', function (event, data, previewId) {
                //上传成功
                if (data.response.code == 1) {
                    $('#' + previewId).addClass(imgList).attr('data-img', data.response.filename);
                }
            }).on('filecustomerror', function (event, id) {
                console.log('=====filecustomerror=====');

            }).on('filesuccessremove', function (event, id) {
                console.log('=====filesuccessremove 移除上传=====');
                load_images = [];
                $('.' + imgList + ':not(#' + id + ')').each(function (i) {
                    load_images[i] = $(this).attr('data-img');
                });
                var temp = imgs.concat(load_images);
                console.log(temp);
                $('input[name="' + $(this).attr('file-upload') + '"]').val(temp.join());
            }).on('filebatchuploadcomplete', function (event, id) {
                console.log('=====filebatchuploadcomplete 上传成功完成=====');
                load_images = [];
                $('.' + imgList).each(function (i) {
                    load_images[i] = $(this).attr('data-img');
                });
                imgs = imgs.concat(load_images);
                console.log(imgs);
                $('input[name="' + $(this).attr('file-upload') + '"]').val(imgs.join());
            }).on('filecleared', function () {
                console.log('=====filecleared 清空功能=====');
                // $('input[name="' + $(this).attr('file-upload') + '"]').val('');
            }).on('filedeleted', function (event, id) { 
                console.log('=====filedeleted 删除已存在=====');
                var lastImgs = [];
                for (let j=0; j < imgs.length; j++) {
                    if (imgs[j] != source_images[id]) {
                        lastImgs.push(imgs[j]);
                    }
                }
                imgs = lastImgs;
                // console.log(id);
                // console.log(lastImgs);
                // console.log(imgs);
                $('input[name="' + $(this).attr('file-upload') + '"]').val(imgs.join());
            }).on('filesorted', function(event, id) {
                console.log('=====filesorted=====');
                let stack = id.stack
                var lastImgs = [];
                for (let k=0; k < stack.length; k++) {
                    lastImgs[k] = source_images[stack[k].key] 
                }
                console.log(imgs);
                imgs = lastImgs.concat(load_images);
                console.log(imgs);
                $('input[name="' + $(this).attr('file-upload') + '"]').val(imgs.join());
            });
        });
 
EOD;
    }
}